const remoteVideo = document.getElementById('remoteVideo');
const filePathInput = document.getElementById('filePath');
const playBtn = document.getElementById('playBtn');
const pauseBtn = document.getElementById('pauseBtn');
const resumeBtn = document.getElementById('resumeBtn');
const startBtn = document.getElementById('startBtn');
const statusDiv = document.getElementById('status');
const noSignalDiv = document.getElementById('noSignal');
const showStatsBtn = document.getElementById('showStatsBtn');
const statsPanel = document.getElementById('statsPanel');
const totalBytesEl = document.getElementById('totalBytes');
const totalLostEl = document.getElementById('totalLost');
const videoBitrateEl = document.getElementById('videoBitrate');
const jitterEl = document.getElementById('jitter');

let connection;
let myPeerConnection;
let trackMonitorInterval;
let statsInterval;
let reconnectDelay = 1000; // WebSocket重连间隔（指数退避）
let heartbeatTimer; // 心跳定时器
let lastStats = { bytes: 0, time: 0 }; // 码率计算用


// 更新状态显示（含视觉提示）
function updateStatus(msg, isError = false) {
    statusDiv.textContent = '状态: ' + msg;
    statusDiv.style.color = isError ? 'red' : '#333';
    console.log('[状态]', msg);
}

// 显示/隐藏无信号提示
function toggleNoSignal(show) {
    noSignalDiv.style.display = show ? 'block' : 'none';
}

// WebSocket连接（带指数退避重连）
function connect() {
    // 销毁旧连接
    if (connection) connection.close();

    connection = new WebSocket('ws://localhost:8080/player');

    // 连接成功：重置重连间隔+启动心跳
    connection.onopen = () => {
        updateStatus('已连接 WebSocket');
        reconnectDelay = 1000; // 重置重连间隔
        startHeartbeat(); // 启动心跳
    };

    // 连接关闭：自动重连
    connection.onclose = (e) => {
        updateStatus(`WebSocket 断开（代码: ${e.code}），${reconnectDelay}ms后重连...`, true);
        toggleNoSignal(true);
        stopHeartbeat(); // 停止心跳

        // 指数退避重连（最大16秒）
        if (reconnectDelay <= 16000) {
            setTimeout(connect, reconnectDelay);
            reconnectDelay *= 2;
        } else {
            updateStatus('重连次数耗尽，请刷新页面', true);
        }
    };

    // 连接错误
    connection.onerror = (e) => {
        updateStatus(`WebSocket 错误: ${e.message}`, true);
    };

    // 接收信令消息
    connection.onmessage = handleSignalingMessage;
}

// 发送消息到服务器
function sendToServer(msg) {
    if (connection && connection.readyState === WebSocket.OPEN) {
        console.log('[发送信令]', msg);
        connection.send(JSON.stringify(msg));
    } else {
        updateStatus('发送失败: WebSocket未连接', true);
    }
}

// 启动心跳（5秒/次）
function startHeartbeat() {
    stopHeartbeat();
    heartbeatTimer = setInterval(() => {
        sendToServer({ id: 'heartbeat' });
    }, 5000);
}

// 停止心跳
function stopHeartbeat() {
    if (heartbeatTimer) {
        clearInterval(heartbeatTimer);
        heartbeatTimer = null;
    }
}

// 创建PeerConnection（优化：ICE配置、状态监听）
function createPeerConnection() {
    // 销毁旧连接
    if (myPeerConnection) {
        myPeerConnection.close();
        clearInterval(trackMonitorInterval);
        clearInterval(statsInterval);
    }

    // 配置：补充TURN（适配跨NAT）
    const config = {
        iceServers: [
            { urls: 'stun:stun.l.google.com:19302' },
            { urls: 'turn:your-turn-server.com', username: 'turn-user', credential: 'turn-pwd' } // 替换为实际TURN
        ],
        iceTransportPolicy: 'all'
    };

    myPeerConnection = new RTCPeerConnection(config);

    // 发送ICE候选
    myPeerConnection.onicecandidate = (event) => {
        if (event.candidate) {
            sendToServer({
                id: 'onIceCandidate',
                candidate: event.candidate.toJSON()
            });
        }
    };

    // 接收媒体流
    myPeerConnection.ontrack = (event) => {
        remoteVideo.srcObject = event.streams[0];
        updateStatus('接收RTP流，开始播放');
        toggleNoSignal(false);
        resumeBtn.disabled = true;

        // 轨道状态监听
        event.track.onmuted = () => {
            updateStatus('警告：视频轨道无流', true);
            toggleNoSignal(true);
        };
        event.track.onunmuted = () => {
            updateStatus('视频轨道恢复');
            toggleNoSignal(false);
        };
        event.track.onended = () => {
            updateStatus('媒体轨道已结束');
            toggleNoSignal(true);
        };
    };

    // 连接状态监听
    myPeerConnection.onconnectionstatechange = () => {
        const state = myPeerConnection.connectionState;
        updateStatus(`连接状态: ${state}`);

        // 连接失败自动重建
        if (state === 'failed') {
            updateStatus('PeerConnection失败，正在重建...', true);
            setTimeout(createPeerConnection, 1000);
        }
    };

    // 轨道监控（2秒/次）
    trackMonitorInterval = setInterval(() => {
        if (!myPeerConnection.getReceivers) return;

        myPeerConnection.getReceivers().forEach((receiver, idx) => {
            if (receiver.track) {
                console.log(`[轨道监控] ${idx}: 类型=${receiver.track.kind}, 状态=${receiver.track.readyState}, 静音=${receiver.track.muted}`);
            }
        });
    }, 2000);

    // RTP统计（3秒/次，可视化展示）
    statsInterval = setInterval(() => {
        if (!myPeerConnection) return;

        myPeerConnection.getStats().then(stats => {
            let totalBytes = 0;
            let totalLost = 0;
            let jitter = 0;
            let videoBytes = 0;
            let currentTime = Date.now();

            stats.forEach(report => {
                if (report.type === 'inbound-rtp') {
                    totalBytes += report.bytesReceived || 0;
                    totalLost += report.packetsLost || 0;
                    if (report.kind === 'video') {
                        jitter = (report.jitter || 0) * 1000; // 转ms
                        videoBytes = report.bytesReceived || 0;

                        // 计算视频码率（kbps）
                        if (lastStats.bytes && currentTime > lastStats.time) {
                            const duration = (currentTime - lastStats.time) / 1000; // 秒
                            const bitrate = Math.round((videoBytes - lastStats.bytes) * 8 / 1024 / duration);
                            videoBitrateEl.textContent = bitrate;
                        }
                        lastStats = { bytes: videoBytes, time: currentTime };
                    }
                }
            });

            // 更新统计面板
            totalBytesEl.textContent = Math.round(totalBytes / 1024); // 转KB
            totalLostEl.textContent = totalLost;
            jitterEl.textContent = Math.round(jitter);
        }).catch(err => {
            updateStatus(`统计获取失败: ${err.message}`, true);
        });
    }, 3000);
}

// 处理信令消息
function handleSignalingMessage(event) {
    try {
        const json = JSON.parse(event.data);
        console.log('[接收信令]', json);

        switch (json.id) {
            case 'startResponse':
                // 设置远端SDP
                myPeerConnection.setRemoteDescription(new RTCSessionDescription({
                    type: 'answer',
                    sdp: json.sdpAnswer
                })).then(() => {
                    updateStatus('SDP协商完成，等待RTP流');
                }).catch(err => {
                    updateStatus(`SDP设置失败: ${err.message}`, true);
                });
                break;

            case 'iceCandidate':
                // 添加远端ICE候选
                myPeerConnection.addIceCandidate(new RTCIceCandidate(json.candidate))
                    .catch(err => updateStatus(`ICE候选添加失败: ${err.message}`, true));
                break;

            case 'playEnd':
                updateStatus('播放结束');
                toggleNoSignal(true);
                resumeBtn.disabled = false;
                clearInterval(trackMonitorInterval);
                clearInterval(statsInterval);
                break;

            case 'error':
                updateStatus(`服务器错误: ${json.message}`, true);
                toggleNoSignal(true);
                resumeBtn.disabled = false;
                break;

            default:
                updateStatus(`未知信令: ${json.id}`, true);
        }
    } catch (err) {
        updateStatus(`信令解析失败: ${err.message}`, true);
    }
}

// 按钮事件绑定
startBtn.onclick = async () => {
    if (myPeerConnection?.connectionState === 'connected') {
        updateStatus('已处于连接状态，无需重复启动');
        return;
    }

    createPeerConnection();
    updateStatus('PeerConnection已创建（纯接收模式）');

    try {
        // 创建Offer（仅接收音视频）
        const offer = await myPeerConnection.createOffer({
            offerToReceiveAudio: true,
            offerToReceiveVideo: true,
            iceRestart: true // 支持ICE重启
        });
        await myPeerConnection.setLocalDescription(offer);

        // 发送Offer
        sendToServer({
            id: 'start',
            sdpOffer: {
                type: offer.type,
                sdp: offer.sdp
            }
        });
        updateStatus('Offer已发送');
    } catch (err) {
        updateStatus(`Offer创建失败: ${err.message}`, true);
    }
};

playBtn.onclick = () => {
    const filePath = filePathInput.value.trim();
    if (!filePath) {
        alert('请输入文件路径');
        return;
    }

    sendToServer({
        id: 'loadAndPlay',
        file: filePath
    });
    updateStatus(`加载请求已发送: ${filePath}`);
};

pauseBtn.onclick = () => {
    sendToServer({ id: 'pause' });
    updateStatus('暂停指令已发送');
    toggleNoSignal(true);
    resumeBtn.disabled = false;
};

resumeBtn.onclick = () => {
    const filePath = filePathInput.value.trim();
    if (!filePath) {
        alert('请输入文件路径');
        return;
    }

    sendToServer({
        id: 'loadAndPlay', // 复用播放指令，后端处理续播
        file: filePath,
        resume: true // 标记为续播
    });
    updateStatus('续播指令已发送');
};

showStatsBtn.onclick = () => {
    statsPanel.style.display = statsPanel.style.display === 'block' ? 'none' : 'block';
    showStatsBtn.textContent = statsPanel.style.display === 'block' ? '隐藏统计' : '显示统计';
};

// 页面卸载前清理资源
window.addEventListener('beforeunload', () => {
    sendToServer({ id: 'stop' }); // 通知后端释放资源
    if (myPeerConnection) myPeerConnection.close();
    if (connection) connection.close();
    stopHeartbeat();
    clearInterval(trackMonitorInterval);
    clearInterval(statsInterval);
});

// 初始化连接
connect();
updateStatus('初始化中...');